/*
    Universe 跨服服务器  
*/

global.clone    = require('clone');
global.util     = require('util');
global.common   = require('./common.js');
global.Player   = require('./logic/player.js').Player;
global.Fighter  = require('./logic/fighter.js').Fighter;
global.Message  = require('./world/message.js').Message;
global.config   = require(require('fs').existsSync('../config.js') ? '../config.js' : './config.js');

var server  = require('./server.js');
var logic   = require('./universe/');
var logger  = require('./logger.js');
require('./global.js');

global.gDBUser = null;
global.gDBReplay = null;
global.gDBWorld = null;

global.gServeWar = null;

logger.init({name:'universe', debug:{backups:10}, error:{backups:2}});
(function main(){
    server.loadConf();
    server.loadDB(function(db){
        global.gDBUser = db.collection('user');
        global.gDBReplay = db.collection('replay');
        global.gDBWorld = db.collection('world');

        INFO('mongodb connected');

        loadUniverse(function(){

            server.startWebServer('universe', config.UniversePort, config.UniverseHost , function(query, res, resp){
                var logicHandler = null;
                var module = logic[query.mod];

                if( module ) {
                    logicHandler = module[query.act];
                }

                if( !logicHandler ) {
                    resp.code = 1;
                    resp.desc = 'act ' + query.act + ' not support in mod ' + query.mod;
                    onReqHandled(res, resp);
                    return;
                }

                logicHandler(query, res, resp);
            });

        });
    }, config.MongodbUniverseName);
})();

function loadUniverse(callback) {
    var counter = 1;
    function onLoad(){
        counter -= 1;
        if( counter <= 0 ) {
            callback && callback();
            timer();
        }
    }
    
    // 加载跨服战数据
    var ServerWar = require('./universe/serverwar.js').ServerWar;
    global.gServerWar = new ServerWar();
    gServerWar.init(function(succ){
        if( !succ ) {
            ERROR("can't load ServerWar");
            process.exit(-1);
        }
        INFO('ServerWar loaded');
        onLoad();
    });
}

function timer() {
    setInterval(function() {
        gServerWar.tick();
    }, 1000);
}
